package com.spring.main.ioc;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import com.spring.main.ioc.annotation.MyAutowired;
import com.spring.main.ioc.annotation.MyController;
import com.spring.main.ioc.annotation.MyService;

public class IOCStartMain {

	private static Map<String, Object> iocMap = new HashMap<>();

	private static String[] packagePath = { "com.spring.main.ioc.service.impl.DemoServiceImpl",
			"com.spring.main.ioc.DemoComtroller" };

	public static String toLowerCase(String param) {
		char[] array = param.toCharArray();
		array[0] += 32;
		return String.valueOf(array);
	}

	public void addIoc() {
		try {
			for (String str : packagePath) {
				Class<?> clazz = Class.forName(str);
				if (clazz.isAnnotationPresent(MyService.class)) {
					MyService myService = clazz.getAnnotation(MyService.class);
					String keyName = myService.value().trim();
					if (!"".equals(keyName)) {
						iocMap.put(keyName, clazz.newInstance());
					} else {
						Class<?>[] interfaces = clazz.getInterfaces();
						for (Class<?> inter : interfaces) {
							iocMap.put(toLowerCase(inter.getSimpleName()), clazz.newInstance());
						}
					}
				}
				if (clazz.isAnnotationPresent(MyController.class)) {
					String beanName = clazz.getSimpleName();
					iocMap.put(toLowerCase(beanName), clazz.newInstance());
				}
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
	}

	public void doAutowired() {
		try {
			for (Entry<String, Object> entry : iocMap.entrySet()) {
				Field[] fields = entry.getValue().getClass().getDeclaredFields();
				for (Field field : fields) {
					if (!field.isAnnotationPresent(MyAutowired.class)) {
						continue;
					}
					String beanName = toLowerCase(field.getType().getSimpleName());
					field.setAccessible(true);
					field.set(entry.getValue(), iocMap.get(beanName));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		IOCStartMain main = new IOCStartMain();
		main.addIoc();
		main.doAutowired();
		DemoComtroller demoComtroller = (DemoComtroller) iocMap.get("demoComtroller");
		String str = demoComtroller.doDemo("123");
		System.out.println(str);
	}

}
